package projectx.web.util;

import java.util.Calendar;

import projectx.core.base.ProjectXProperties;
import projectx.core.base.ProjectXUserException;

public final class ServiceTimeChecker {

	// --------------------------------------------------------------------------
	// S T A T I C M E M B E R S
	//
	// --------------------------------------------------------------------------
	private static final String startTime = ProjectXProperties.getProperty(
			"service.start.time", "");
	private static final String stopTime = ProjectXProperties.getProperty(
			"service.stop.time", "");

	// --------------------------------------------------------------------------
	// M E M B E R S
	//
	// --------------------------------------------------------------------------
	private final boolean _requireCheck;
	private String _amStopTime;

	// --------------------------------------------------------------------------
	// C O N S T R U C T O R S
	//
	// --------------------------------------------------------------------------
	public ServiceTimeChecker() {

		_requireCheck = (startTime.length() > 0 && stopTime.length() > 0) ? true
				: false;

		if (!_requireCheck) {
			return;
		}

		int stopHour = Integer.parseInt(stopTime.substring(0, 2));
		if (_requireCheck && stopHour > 24) {
			_amStopTime = "0" + (stopHour - 24) + ":"
					+ stopTime.substring(3, 5);
		}
	}

	// --------------------------------------------------------------------------
	// M E T H O D S
	//
	// --------------------------------------------------------------------------
	public void check() throws ProjectXUserException {

		if (!_requireCheck) {
			return;
		}

		String curTime = getCurrentTime();

		boolean isServiceTime;

		if (_amStopTime == null) {
			isServiceTime = isServiceTime(curTime, startTime, stopTime);
		} else {
			boolean rc1 = isServiceTime(curTime, startTime, "24:00");
			boolean rc2 = isServiceTime(curTime, "00:00", _amStopTime);
			isServiceTime = rc1 | rc2;
		}

		if (!isServiceTime) {
			throw new ProjectXUserException("E0300", startTime, stopTime);
		}
	}

	private String getCurrentTime() {

		Calendar cal = Calendar.getInstance();

		int curHour = cal.get(Calendar.HOUR_OF_DAY);
		int curMinute = cal.get(Calendar.MINUTE);

		StringBuffer sb = new StringBuffer();

		if (curHour < 10)
			sb.append('0');
		sb.append(curHour);
		sb.append(':');
		if (curMinute < 10)
			sb.append('0');
		sb.append(curMinute);

		return sb.toString();
	}

	private boolean isServiceTime(String curTime, String startTime,
			String stopTime) {

		if (startTime.compareTo(curTime) <= 0
				&& stopTime.compareTo(curTime) > 0) {
			return true;
		} else {
			return false;
		}
	}
}
